<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/techshine_war/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/techshine_war/bootstrap/bootstrap.css" media="all">
    <script src="/techshine_war/layui/layui.all.js" charset="utf-8"></script>
    <script src="/techshine_war/js/jquery.js"></script>
    <script src="/techshine_war/js/global.js" charset="utf-8"></script>
    <!--<script src="../release/wangEditor.js" charset="utf-8"></script>
    <script src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>-->
    <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
    <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
    <style>
        .layui-form-label {
            width: 120px;
        }

        .layui-input {
            width: 95%;
        }
        .editor-toolbar {
            border: 1px solid #ccc;
        }

        .editor-text-area {
            border: 1px solid #ccc;
            border-top: 0;
            height: 400px;
        }
    </style>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>

<body>
<form class="layui-form" id="edit-form" action="" style="margin: 20px;">

    <div class="layui-form-item">
        <label class="layui-form-label">所属菜单</label>
        <div class="layui-input-block">
            <select name="menuid" id="menuid" lay-verify="required" required>
                <option value="1">公司介绍</option>
                <option value="2" selected="selected">产品中心</option>
                <option value="3">解决方案</option>
                <option value="4">技术支持</option>
                <option value="5">毕昇杯</option>
                <option value="6">联系我们</option>

            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" id="name" lay-verify="name" lay-reqtext="名称不能为空" placeholder="请输入1-50字" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">类别</label>
        <div class="layui-input-block">
            <input type="text" name="category" id="category" lay-verify="category" lay-reqtext="类别不能为空" placeholder="请输入1-50字" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">型号</label>
        <div class="layui-input-block">
            <input type="text" name="model" id="model" lay-verify="model" lay-reqtext="型号不能为空" placeholder="请输入1-50字" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">序号</label>
        <div class="layui-input-block">
            <input type="number" name="seq" id="seq" lay-verify="seq" lay-reqtext="序号不能为空" value="1" placeholder="请输入" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">缩略图</label>
        <div class="layui-upload">
            <button type="button" class="layui-btn" id="test1">上传图片</button><span>建议图片尺寸100*100</span>
            <img class="layui-upload-img" id="demo1" style="width: 100px;height: 100px;">
            <p id="demoText"></p>
        </div>
    </div>
    <input type="hidden" id="imgurl" name="imgurl" value="" />
    <div id="htmlvaldiv">
        <label class="layui-form-label">文章内容</label>
        <div>
            <div id="editor-toolbar" class="editor-toolbar"></div>
            <div id="editor-text-area" class="editor-text-area"></div>
        </div>
        <textarea id="htmlval" name="htmlval" style="display: none;"></textarea>
    </div>
    <div style="text-align: center;">
        <input type="hidden" id="id" name="id" value="" />
        <button type="submit" class="layui-btn" lay-submit="" lay-filter="formDemo">立即提交</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="closePage()">关闭</button>
    </div>

</form>
<script>
    //Demo
    var id = getQueryString("id");

    var form;
    var submiting = false;
    layui.use(['layer', 'form','upload'], function() {
        //var layedit = layui.layedit;
        var upload = layui.upload;
        var form = layui.form;
        initlist();
        initedit();
        initupload(upload);
        initData(form);
        //自定义验证规则
        form.verify({
            name: function(value) {
                if(value.length < 1 || value.length > 50) {
                    return '名称长度1-50';
                }

            },
            model: function(value) {
                if(value.length < 1 || value.length > 50) {
                    return '型号长度1-50';
                }

            },
            category: function(value) {
                if(value.length < 1 || value.length > 50) {
                    return '类别长度1-50';
                }

            },
            seq: function(value) {
                if(value.length < 1) {
                    return '请输入序号';
                }

            },

        });
        //监听提交
        form.on('submit(formDemo)', function(data) {
            if(submiting) {
                return false;
            }

            $("#htmlval").val(editor.getHtml());
            var data = $("form").serializeArray();
            console.info(JSON.stringify(data.field))
            $.ajax({
                type: "post",
                url: '/techshine_war/equ/insert',
                async: false,
                data: data,
                success: function(res) {
                    submiting = true;
                    parent.reload();
                    closePage();
                }
            });
            return false;
        });
        form.on('select(menutype)', function(data) {
            var sval = data.value;
            if(sval == '1') {
                $("#htmlvaldiv").show()
            } else {
                $("#htmlvaldiv").hide()
            }
            form.render(); //更新全部
            form.render('select');
        });
    });

    function initData(form) {
        if(id != null && id.length > 0) {
            $.ajax({
                type: "get",
                url: '/techshine_war/equ/queryByKey?id=' + id,
                async: false,
                success: function(res) {
                    echoEdit(res.result);
                    $("#seq").val(res.result.seq);
                    $("#name").val(res.result.name);
                    $("#menuid").val(res.result.menuid);
                    $("#model").val(res.result.model);
                    $("#category").val(res.result.category);

                    $("#imgurl").val(res.result.imgurl);
                    $('#demo1').attr('src', res.result.imgurl);

                    $("#htmlval").val(res.result.htmlval);
                    if(res.result.htmlval!=null){
                        editor.setHtml(res.result.htmlval)
                    }
                    form.render('select');
                }
            });
        }else{
            form.render('select');
        }
    }
    var editor ;
    function initedit(){
        const E = window.wangEditor;
        // Change language
        const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
        E.i18nChangeLanguage(LANG)

        const editorConfig = { MENU_CONF: {} }
        editorConfig.MENU_CONF['uploadImage'] = {
            server: '/techshine_war/menu/uploadpic?imgtype=1',
            // server: '/api/upload-img-10s', // test timeout
            // server: '/api/upload-img-failed', // test failed
            // server: '/api/xxx', // test 404

            timeout: 5 * 1000, // 5s

            fieldName: 'custom-fileName',
            meta: { token: 'xxx', a: 100 },
            metaWithUrl: true, // join params to url
            headers: { Accept: 'application/json' },
            maxFileSize: 10 * 1024 * 1024, // 10M

            base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

            onBeforeUpload(file) {
                //console.log('onBeforeUpload', file)

                return file // will upload this file
                // return false // prevent upload
            },
            onProgress(progress) {
                //console.log('onProgress', progress)
            },
            onSuccess(file, res) {
                //console.info(1)
                //return res.data[0]
                //console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
                //alert(res.message)
                console.log('onFailed', file, res)
            },
            onError(file, err, res) {
                //alert(err.message)
                console.error('onError', file, err, res)
            },
            customInsert(res, insertFn) {
                console.info(res)
                //  console.log('customInsert', res)
                // const imgInfo = res.data[0];
                // const { url, alt, href } = imgInfo
                //  if (!url) throw new Error(`Image url is empty`)

                //   console.log('Your image url ', url)
                insertFn(res.data[0])
            }

        }

        editor = E.createEditor({
            selector: '#editor-text-area',
            html: '请输入文章',
            config: editorConfig,
            onChange(editor) {
                console.log(editor.getHtml())
                // 选中文字
                const selectionText = editor.getSelectionText()
                document.getElementById('selected-length').innerHTML = selectionText.length
                // 全部文字
                const text = editor.getText().replace(/\n|\r/mg, '');
                console.info(text)
            }
        })
        const toolbar = E.createToolbar({
            editor,
            selector: '#editor-toolbar',
            // config: {}
        })
    }
    var uploadInst;
    function initupload(upload){
        //普通图片上传
        uploadInst = upload.render({
            elem: '#test1'
            ,url: '/techshine_war/menu/uploadpic?imgtype=1'
            ,accept:'jpg|png|gif|bmp|jpeg'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.errno > 0){
                    return layer.msg('上传失败');
                }else{
                    $("#imgurl").val((res.data)[0])
                }
                //上传成功
            }
            ,error: function(){
                $("#imgurl").val("")
                //演示失败状态，并实现重传
                layer.msg("图片上传失败")
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
    }
    function initlist(){
        $.ajax({
            type:"get",
            url: '/techshine/menu/queryList?menutype=2',
            async:false,
            success:function(res){
                var liststr="";
                $.each(res.result, function() {
                    liststr+='<option value="'+this.id+'">'+this.name+'</option>'
                });
                $("#menuid").html(liststr);

            }
        });
    }
</script>
</body>

</html>